package CyclicBarrier_6;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class 并行计算_矩阵运算 {
    private static final int ROWS = 4;
    private static final int COLS = 100;
    private static final int[][] matrix = new int[ROWS][COLS];
    private static final int[] rowSums = new int[ROWS];
    private static int totalSum = 0;

    public static void main(String[] args) {
        // 初始化矩阵
        for (int i = 0; i < ROWS; i++) {
            for (int j = 0; j < COLS; j++) {
                matrix[i][j] = (int)(Math.random() * 10);
            }
        }

        final CyclicBarrier barrier = new CyclicBarrier(ROWS, new Runnable() {
            public void run() {
                // 所有行计算完成后执行
                for (int sum : rowSums) {
                    totalSum += sum;
                }
                System.out.println("矩阵总和: " + totalSum);
            }
        });

        // 创建计算线程
        for (int i = 0; i < ROWS; i++) {
            final int row = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        int sum = 0;
                        for (int j = 0; j < COLS; j++) {
                            sum += matrix[row][j];
                            Thread.sleep(1); // 模拟计算时间
                        }
                        rowSums[row] = sum;
                        System.out.println("行 " + row + " 计算完成，和: " + sum);
                        barrier.await();
                    } catch (InterruptedException | BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}